package controllers;

import java.io.IOException;
import java.util.List;

import com.google.gson.JsonObject;

import models.AbstractProfile;
import models.SocialProfile;
import models.User;
import play.data.validation.Required;
import play.libs.OAuth2;
import play.libs.WS;
import play.mvc.Controller;
import play.mvc.With;
import play.mvc.results.Redirect;

@With(Secure.class)
public class SocialProfiles extends CRUD
{
	public static OAuth2	FACEBOOK	= new OAuth2(
												"https://graph.facebook.com/oauth/authorize",
												"https://graph.facebook.com/oauth/access_token",
												"388171657886328",
												"749b3e6691f50b63a665b2f87e4cf2f2");
	public static boolean	logoutFlag	= true;

	/**
	 * The router matches HTTP requests to action invocations
	 * 
	 * @author Rania Said
	 * @return URL
	 */
	public static String authURL()
	{
		System.out.println("Running in SocialProfiles.authURL method");
		return play.mvc.Router.getFullUrl("SocialProfiles.auth");
	}

	/**
	 * This method is the implementation of OAuth 2.0 protocol for Facebook
	 * login. After retrieving the access token of an OSN account, information
	 * of this account is persisted in the database.
	 * 
	 * @author Rania Said
	 */
	public static void auth()
	{
		System.out.println("Running in SocialProfiles.auth method");
		User u = Users.getCurrentUser();
		if (u == null)
		{
			try
			{
				Secure.login();
			}
			catch (Throwable e)
			{

			}
		}
		else
		{
			if (OAuth2.isCodeResponse())
			{
				System.out.println("The code response is okay");

				OAuth2.Response response = FACEBOOK
						.retrieveAccessToken(authURL());
				System.out.println("RESPONSE.accessToken   : "
						+ response.accessToken);

				for (int i = 0; i < u.abstractProfileList.size(); i++)
				{
					System.out.println("inside the for loop");
					if (u.abstractProfileList.get(i).inConnection)
					{
						System.out.println(u.abstractProfileList.get(i).name
								+ " is in Connection");

						SocialProfile tempSocialProfile = new SocialProfile(
								response.accessToken,
								u.abstractProfileList.get(i));

						JsonObject me = WS
								.url("https://graph.facebook.com/me?access_token=%s",
										WS.encode(response.accessToken)).get()
								.getJson().getAsJsonObject();

						long tempID = me.get("id").getAsLong();
						tempSocialProfile.uid = tempID;

						String gender = me.get("gender").getAsString();
						tempSocialProfile.gender = gender;

						String displayName = me.get("name").getAsString();
						tempSocialProfile.displayName = displayName;

						String link = me.get("link").getAsString();
						tempSocialProfile.link = link;

						String username = me.get("username").getAsString();
						tempSocialProfile.username = username;

						String pp = "https://graph.facebook.com/" + tempID
								+ "/picture";
						tempSocialProfile.ppLink = pp;

						String updated_time = me.get("updated_time")
								.getAsString();
						System.out.println(updated_time);
						tempSocialProfile.updated_time = updated_time;

						if (!u.abstractProfileList.get(i).profileList
								.contains(tempSocialProfile))
						{
							u.abstractProfileList.get(i).profileList
									.add(tempSocialProfile);
							System.out
									.println(u.abstractProfileList.get(i).profileList
											.size());

							u.abstractProfileList.get(i).inConnection = false;
							u.abstractProfileList.get(i).save();
							u.save();

							System.out.println("User saved");
							AbstractProfiles
									.manageIdentity(u.abstractProfileList
											.get(i).name);
						}
						else
						{
							// Redundancy
							flash.error("This account is already connected to this ");
							AbstractProfiles
									.manageIdentity(u.abstractProfileList
											.get(i).name);
						}
					}
				}
			}
			else
			{
				System.out.println("Code did not respond . . .");
				System.out.println("START OF OAUTH DIALOGUE");
				String RedirectURL = "https://www.facebook.com/dialog/oauth?"
						+ "client_id="
						+ "388171657886328"
						+ "&redirect_uri="
						+ authURL()
						+ "&scope="
						+ "user_status,user_photos,friends_status,user_checkins";
				throw new Redirect(RedirectURL);
			}
		}
	}

	/**
	 * This method logs out a user of a certain OSN using the persisted access token of this OSN account
	 * 
	 * @author Rania Said
	 * @param accessToken
	 *            : the access token of the OSN account that a user needs to log
	 *            out from.
	 */
	public static void logUserOut(String accessToken)
	{
		System.out.println("Running in SocialProfiles.logUserOut method");
		logoutFlag = false;
		// The default system browser under windows.
		final String WIN_PATH = "rundll32";
		// The flag to display a url.
		final String WIN_FLAG = "url.dll,FileProtocolHandler";
		String logoutString = "https://www.facebook.com/logout.php?next="
				+ authURL() + "&access_token=" + accessToken;
		System.out.println(logoutString);
		String cmd = WIN_PATH + " " + WIN_FLAG + " " + logoutString;

		// where {0} is my URL that FB will redirect to and {1} is the users
		// valid access token.
		try
		{
			System.out.println("Log out process is about to be executed");
			Process p = Runtime.getRuntime().exec(cmd);
		}
		catch (IOException x)
		{
			// couldn't exec browser
			System.err.println("Could not invoke browser, command=" + cmd);
			System.err.println("Caught: " + x);
		}
	}

}
